<template>
  <div class="order_view">
    <!-- <Form :searchForm="propsForm" ref="formRef" @my-btn="handBtnClick"></Form> -->
    <el-card shadow="never" class="card-com">
      <div class="card-1">
        <searchPanel @refresh="handBtnClick('reset')">
          <!-- 查询面板 -->
          <template v-slot:search>
            <el-form :inline="true" :model="initParams.condition" class="demo-form-inline" :label-width="120">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="渠道Key">
                    <ChannelSelect v-model:select-value="initParams.condition.channelCodeList" :multiple="true" @my-change="handBtnClick('search')"></ChannelSelect>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品编码">
                    <el-select multiple v-model="initParams.condition.productCodeList" style="width: 100%"
                      @change="handBtnClick('search')" placeholder="请选择产品编码" filterable clearable collapse-tags
                      collapse-tags-tooltip>
                      <el-option v-for="item in listCollect.productList" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="供应商编码">
                    <el-select multiple v-model="initParams.condition.supplierCodeList" style="width: 100%"
                      @change="handBtnClick('search')" placeholder="请选择供应商编码" filterable clearable collapse-tags
                      collapse-tags-tooltip>
                      <el-option v-for="item in listCollect.supplierList" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="订单号">
                    <el-input @keyup.enter.native="handBtnClick('search')" @clear="handBtnClick('search')"
                      v-model="initParams.condition.orderNo" clearable placeholder="请输入订单号" />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="手机号">
                    <el-input @keyup.enter.native="handBtnClick('search')" @clear="handBtnClick('search')"
                      v-model="initParams.condition.mobile" clearable placeholder="请输入手机号" />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="订单状态">
                    <el-select collapse-tags-tooltip v-model="initParams.condition.orderStatus"
                      @change="handBtnClick('search')" style="width: 100%" placeholder="请选择状态" clearable>
                      <el-option v-for="item in orderStatus" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="操作时间">
                    <TimePicker v-model:operateTime="operateTime" style="width: 100%;" @timeChange="operateChange">
                    </TimePicker>
            
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="成功时间">
                    <TimePicker v-model:operateTime="successTime" style="width: 100%;" @timeChange="successChange">
                    </TimePicker>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="运营商">
                    <el-select collapse-tags-tooltip v-model="initParams.condition.isp" @change="handBtnClick('search')"
                      style="width: 100%" placeholder="请选择运营商" clearable>
                      <el-option v-for="item in ispEnum" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="是否退订">
                    <el-select collapse-tags-tooltip v-model="initParams.condition.isUnsubscribe"
                      @change="handBtnClick('search')" style="width: 100%" placeholder="请选择" clearable>
                      <el-option v-for="(item, index) in isUnsubscribe" :key="index" :value="index"
                        :label="item"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row justify="end">
                <el-button type="primary" @click="handBtnClick('search')">查询</el-button>
                <el-button @click="handBtnClick('reset')">重置</el-button>
              </el-row>
            </el-form>
          </template>
          <!-- 字段添加 -->
          <template v-slot:edit>
            <el-button :icon="Download" v-permission="'INVENTORY_PACKAGE_ORDER:EXPORT'" @click="btnDown" 
              title="下载订单列表"></el-button>
            <el-button :icon="List" v-permission="'INVENTORY_PACKAGE_ORDER:EXPORT'" @click="btnDownList"
              title="查看下载订单列表"></el-button>
            <el-button :icon="initParams.isShow?'Hide':'View'"  @click="handleView"
              :title="initParams.isShow ? '隐藏敏感数据':'查看敏感数据'"></el-button>

            <el-dropdown :hide-on-click="false" style="margin: 0 10px" trigger="click">
              <el-button title="过滤表头">
                <el-icon :size="18">
                  <Grid />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-checkbox-group v-model="selectTitle" size="small" @change="checkboxChange">
                    <el-dropdown-item v-for="item in showTitle" :key="item.prop">
                      <el-checkbox :label="item.label" :value="item.prop" />
                    </el-dropdown-item>
                  </el-checkbox-group>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </searchPanel>
      </div>
      <div class="card-2">
        <OnlyTable ref="onlyTableRef" class="card-2" :tableProps="tableProp" :pageTotal="pageData.total" @get-page="handPage"
          :tableData="pageData.tableData" :tableHeight="pageData.tableHeight" :loading="pageData.loadIng">
          <template #orderStatus="scope">
            {{ scope.row.orderStatus&&hasOrder(scope.row.orderStatus) }}
          </template>
          <template #isUnsubscribe="scope">
            {{ isUnsubscribe[scope.row.isUnsubscribe] }}
          </template>
          <template #isp="scope">
            {{ scope.row.isp&&hasIsp(scope.row.isp) }}
          </template>
          <template #handle="scope">
            <el-button type="primary" size="small" v-permission="'INVENTORY_PACKAGE_ORDER:DETAIL'" link
              @click="handTableRow(scope.row)">详情</el-button>
          </template>
        </OnlyTable>
      </div>
    </el-card>

    <Dialog :dialogProps="dialogProps" ref="dialogTwo"></Dialog>
    <downList ref="downListRef" @flash="btnDownList"></downList>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import _ from "lodash";
import config from "./config/index.ts";
import { Search, Refresh, Bottom, View,Hide, Download, List } from "@element-plus/icons-vue";
import { orderListStore } from "./pageStore.ts";
import {
  getOrderList,
  getOrderListHide,
  getOrderInfo,
  getProductListAll,
  getSupplierAll,
} from "@/api/product";
import {useComListData} from "@/store/list.ts"
import { exportExportOrderApiPost } from "@/api/fileDown";
import { channelListApiPost } from "@/api/userMangement";
import mittBus from '@/utils/mitt';
import Dialog from "@/components/Dialog/index.vue";
import { storeToRefs } from "pinia";
import { useEnumStore } from "@/store/enumeration.ts";
import {menuStore} from "@/store/menu.ts"
import TimePicker from "@/components/customSon/timePicker.vue";

const {listCollect,getSupplierAllList,getProListAll}  = useComListData()
const { orderStatus, ispEnum, isUnsubscribe } = storeToRefs(useEnumStore())
const { dialogProps } = config;
const { tableProp } = storeToRefs(orderListStore());
const {sensitive} = menuStore()
const showData = ref(false)
const onlyTableRef=ref()
const downListRef = ref<{ show: (title: string, row?: any) => void }>();
const selectTitle = ref<any>([]);

let dialogTwo = ref<{ handEcho: (flag: boolean, row: any) => void }>();
let operateTime = ref([]);
let successTime = ref([]);
let initParams = ref({
  pageNum: 1,
  pageSize: 20,
  condition: {
    channelCodeList: null,
    productCodeList: null,
    supplierCodeList: null,
    orderNo: null,
    mobile: null,
    orderStatus: null,
    handTime: null,
    orderSuccessTimeStart: null,
    orderSuccessTimeEnd: null,
    orderTimeStart: null,
    orderTimeEnd: null,
    isp: null,
    isUnsubscribe: null,
  },
  isShow: false,
  orders: ["created_time desc"],
});
const showFun=(str:string)=>{
 const arr =  sensitive && sensitive.filter((item:any)=>item.code == str)
 if(arr && arr.length){
  return true
 }
 return false
}
const pageData = reactive({
  loadIng: false,
  tableData: [],
  total: 0,
  tableHeight: 500,
  productList: [],
});




const hasOrder=(order:any)=>{
    let obj = orderStatus.value.find((item) => item.key == order)
    if (obj) {
      return obj.value
    } else {
      return "未知状态"
    }
}
const hasIsp=(order:any)=>{
    let obj = ispEnum.value.find((item) => item.key == order)
    if (obj) {
      return obj.value
    } else {
      return "未知状态"
    }
}
const btnDown = async () => {
  try {
    let res;
    res = await exportExportOrderApiPost(initParams.value);
    if (res && res.code == 20000) {
      ElMessage({
        type: "success",
        message:
          "下载成功 请查看下载列表 未出现下载数据 可等待在刷新下载列表！",
      });
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: "下载失败 请稍后再试！",
    });
  }
};
const btnDownList = () => {
  downListRef.value?.show("订单下载列表", "inventoryPackageOrder");
};
const successChange = (time: any) => {
  if (time && time.length > 0) {
    initParams.value.condition.orderSuccessTimeStart = time[0];
    initParams.value.condition.orderSuccessTimeEnd = time[1];
  } else {
    initParams.value.condition.orderSuccessTimeStart = null;
    initParams.value.condition.orderSuccessTimeEnd = null;
  }
  handBtnClick("search");
};
const operateChange = (time: any) => {
  if (time && time.length > 0) {
    initParams.value.condition.orderTimeStart = time[0];
    initParams.value.condition.orderTimeEnd = time[1];
  } else {
    initParams.value.condition.orderTimeStart = null;
    initParams.value.condition.orderTimeEnd = null;
  }
  handBtnClick("search");
};

const handleView = (bol: boolean) => {
  initParams.value.isShow = !initParams.value.isShow;
    init('search')
};
const initCompPag = () => {
  initParams.value.pageNum = 1;
  initParams.value.pageSize = 20;
};

const checkboxChange = (val: string[]) => {
  pageData.loadIng = true;
  // 进入的 全部为 true 没有的为false
  tableProp.value.propsList = tableProp.value.propsList.map((item: any) => {
    if (val.includes(item.prop)) {
      return {
        ...item,
        hidden: true,
      };
    } else if (item.label == "操作") {
      return {
        ...item,
        hidden: true,
      };
    } else {
      return {
        ...item,
        hidden: false,
      };
    }
  });
  pageData.loadIng = false;
};
const showTitle = computed(() => {
  return tableProp.value.propsList.filter((it) => it.label != "操作");
});
onMounted(() => {
  selectTitle.value = tableProp.value.propsList
    .filter((it) => it.hidden && it.label != "操作")
    .map((item) => item.prop);

  init();
  getSupplierAllList()
  getProListAll({})
});

const init = async () => {
  pageData.loadIng = true;
  // 做一个判断
  getOrderList(initParams.value).then((res) => {
    pageData.loadIng = false;
    let {
      data: { records, total },
    } = res;
    pageData.tableData = records;
    pageData.total = total;
    mittBus.emit('scrollUpdate')
    if (records && records.length > 0) {
      if (records[0]["mobile"].includes("*")) {
        initParams.value.isShow = false;
      }
    }
  });
};

/*分页*/
const handPage = async (params: any) => {
  if (params) {
    initParams.value.pageNum = params.pageNum;
    initParams.value.pageSize = params.pageSize;
  }
  init();
};

const handBtnClick = (type: string) => {
  if (type == "search") {
    initCompPag();
    init();
  } else if (type == "reset") {
    onlyTableRef.value.initPagination()
    operateTime.value = [];
    successTime.value = [];
    Object.keys(initParams.value.condition).forEach((it: any) => {
      initParams.value.condition[it] = null;
    });
    initCompPag();
    init();
  }
};

const handTableRow = (row: any) => {
  getOrderInfo({ id: row.id }).then((res) => {
    if (res.code == 20000) {
      dialogTwo.value?.handEcho(true, res.data);
    }
  });
};
</script>

<style lang="scss" scoped>
.order_view {
  height: calc(100vh - 70px);

  .card-com {
    display: flex;
    flex-direction: column;
    // height: 100%;

    .card-2 {
      flex-grow: 1;
    }
  }
}
</style>
